package com.sdksoft.readcard.testConfig

import android.os.Bundle
import android.view.View
import android.widget.CompoundButton
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.children
import com.csht.cache.SpUtlils
import com.csht.enums.DecodeImageType
import com.sdksoft.readcard.R
import com.sdksoft.readcard.databinding.ActivityTestConfigBinding
import com.sdksoft.readcard.testConfig.bean.ConfigBean
import com.sdksoft.readcard.utils.ReadCardManagerUtil
import com.sdksoft.readcard.utils.ReadCardManagerUtil.Companion.READ_CONFIG_KEY
import com.csht.utils.BytesUtils
import com.csht.utils.HHTipUtils
import com.csht.utils.JsonUtils

/**
 * 内测版本，需要的参数修改
 */
class TestConfigActivity : AppCompatActivity(), View.OnClickListener,
    CompoundButton.OnCheckedChangeListener {

    private lateinit var activityTestConfigBinding: ActivityTestConfigBinding

    private var configBean: ConfigBean? = null

    private var checkedIdLast = -1
    private val listRadioButton: MutableList<RadioButton> = arrayListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        activityTestConfigBinding = ActivityTestConfigBinding.inflate(layoutInflater)
        setContentView(activityTestConfigBinding.root)

        activityTestConfigBinding.apply {
            SpUtlils.getString(READ_CONFIG_KEY, "").let {
                try {
                    if (it.isNotEmpty()) {
                        configBean = JsonUtils.gson.fromJson<ConfigBean>(it, ConfigBean::class.java)
                    }
                } catch (e: Exception) {
                }
            }
            listRadioButton.apply {
                add(rbNoImage)
                add(rbServerImage)
                add(rbLocalImage)
                add(rbServerImageFinger)
                add(rbLocalImageFinger)
            }
            if (configBean == null) {
                configBean = ConfigBean()
            }
            configBean?.apply {
                etAppid.setText(appid)
                etAppkey.setText(appkey)
                etAppSecret.setText(appsecret)
                etIp.setText(ip)
                etPort.setText(port.toString())
                etSamcode.setText(samACCode)
                etByIp.setText(standbyIp)
                etByPort.setText(standbyPort.toString())
                etSerialFile.setText(deviceFilePath)
                etSerialBaudrate.setText(baudrate.toString())
                cbOpenLog.isChecked = openLog
                cbSound.isChecked = openSound
                cbLocalcache.isChecked = openLocalCache
                cbNeedPhoto.isChecked = isNeedIdCardPhoto
                cbNeedPassportPhoto.isChecked = isPassportPhoto
                cbNeedMoveCard.isChecked = isNeedMoveCard
                cbIsAsynApi.isChecked = isAsynApiResult

                when (decodeImageType) {
                    DecodeImageType.NO_IMAGE.codeType -> {
                        checkedIdLast = R.id.rb_no_image
                    }
                    DecodeImageType.SERVER_DECODE.codeType -> {
                        checkedIdLast = R.id.rb_server_image
                    }
                    DecodeImageType.LOCAL_DECODE.codeType -> {
                        checkedIdLast = R.id.rb_local_image
                    }
                    DecodeImageType.SERVER_DECODE_FINGER.codeType -> {
                        checkedIdLast = R.id.rb_server_image_finger
                    }
                    DecodeImageType.LOCAL_DECODE_FINGER.codeType -> {
                        checkedIdLast = R.id.rb_local_image_finger
                    }
                }
                changedRadioButton()
            }

            buSave.setOnClickListener(this@TestConfigActivity)
            buAddBy.setOnClickListener(this@TestConfigActivity)
            buRemoveBy.setOnClickListener(this@TestConfigActivity)
            buSaveSerial.setOnClickListener(this@TestConfigActivity)

            cbLocalcache.setOnCheckedChangeListener(this@TestConfigActivity)
            cbSound.setOnCheckedChangeListener(this@TestConfigActivity)
            cbOpenLog.setOnCheckedChangeListener(this@TestConfigActivity)
            cbNeedPhoto.setOnCheckedChangeListener(this@TestConfigActivity)
            cbNeedPassportPhoto.setOnCheckedChangeListener(this@TestConfigActivity)
            cbNeedMoveCard.setOnCheckedChangeListener(this@TestConfigActivity)
            cbIsAsynApi.setOnCheckedChangeListener(this@TestConfigActivity)
            listRadioButton.forEach {
                it.setOnClickListener(this@TestConfigActivity)
            }
        }
    }

    override fun onClick(v: View) {
        activityTestConfigBinding.apply {
            ReadCardManagerUtil.init.getReadSettingBuilder().apply {
                try {
                    when (v.id) {
                        R.id.bu_save -> {
                            configBean?.apply {
                                if (etAppid.text.toString().trim().isEmpty()) {
                                    HHTipUtils.getInstance().showToast(baseContext,"请填写appid")
                                }
                                if (etIp.text.toString().trim().isEmpty()) {
                                    HHTipUtils.getInstance().showToast(baseContext,"请填写ip")
                                }
                                if (etPort.text.toString().trim().isEmpty()) {
                                    HHTipUtils.getInstance().showToast(baseContext,"请填写端口")
                                }
                                appid = etAppid.text.toString().trim()
                                appkey = etAppkey.text.toString().trim()
                                appsecret = etAppSecret.text.toString().trim()
                                ip = etIp.text.toString().trim()
                                port = etPort.text.toString().trim().toInt()
                                buildAppId(appid, appkey, appsecret)
                                buildIpAndPort(
                                    ip,
                                    port
                                )
                                samACCode = etSamcode.text.toString().trim()
                                if (samACCode.isNotEmpty() && samACCode.length == 32) {
                                    // 设置SAM卡的AC代码（默认为空，需要时请设置）
                                    buildSAMCode(BytesUtils.hexStringToBytes(samACCode))
                                } else {
                                    buildSAMCode(byteArrayOf())
                                }
                            }
                        }
                        R.id.bu_add_by -> {
                            configBean?.apply {
                                standbyIp = etByIp.text.toString().trim()
                                standbyPort = etByPort.text.toString().trim().toInt()

                                buildStandbyIpAndPort(
                                    standbyIp,
                                    standbyPort
                                )
                            }
                        }
                        R.id.bu_remove_by -> {
                            buildRemoveIpAndPort(
                                etByIp.text.toString().trim(),
                                etByPort.text.toString().trim().toInt()
                            )
                        }
                        R.id.bu_save_serial -> {
                            configBean?.apply {
                                deviceFilePath = etSerialFile.text.toString().trim()
                                baudrate = etSerialBaudrate.text.toString().trim().toInt()

                                buildSerialPort(
                                    deviceFilePath,
                                    baudrate
                                )
                            }
                        }
                        else -> {
                            if (v.id != checkedIdLast && v is RadioButton) {
                                listRadioButton.forEach { rb ->
                                    if (rb.id == checkedIdLast) {
                                        rb.isChecked = false
                                    }
                                }
                                checkedIdLast = v.id
                                changedRadioButton()
                                return@apply
                            }
                        }
                    }
                    HHTipUtils.getInstance().showToast(baseContext, "操作成功")
                } catch (e: Exception) {
                    HHTipUtils.getInstance().showToast(baseContext, "操作失败," + e.message)
                }
            }
        }
    }

    override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
        ReadCardManagerUtil.init.getReadSettingBuilder().apply {
            when (buttonView.id) {
                R.id.cb_localcache -> {
                    configBean?.openLocalCache = isChecked
                    buildOpenLocalCache(isChecked)
                }
                R.id.cb_openLog -> {
                    configBean?.openLog = isChecked
                    buildOpenLog(isChecked, "")
                }
                R.id.cb_sound -> {
                    configBean?.openSound = isChecked
                    buildOpenSound(isChecked)
                }
                R.id.cb_needPhoto -> {
                    configBean?.isNeedIdCardPhoto = isChecked
                    buildNeedIdCardPhoto(isChecked)
                }
                R.id.cb_needPassportPhoto -> {
                    configBean?.isPassportPhoto = isChecked
                    buildNeedPassportPhoto(isChecked)
                }
                R.id.cb_needMoveCard -> {
                    configBean?.isNeedMoveCard = isChecked
                    buildIsNeedMoveCard(isChecked)
                }
                R.id.cb_isAsynApi -> {
                    configBean?.isAsynApiResult = isChecked
                    buildIsAsynApiResult(isChecked)
                }
            }
            HHTipUtils.getInstance().showToast(baseContext, "操作成功")
        }
    }

    private fun changedRadioButton() {
        listRadioButton.forEach {
            if (it.id == checkedIdLast) {
                it.isChecked = true
                return@forEach
            }
        }
        ReadCardManagerUtil.init.getReadSettingBuilder().apply {
            when (checkedIdLast) {
                R.id.rb_no_image -> {
                    configBean?.decodeImageType = DecodeImageType.NO_IMAGE.codeType
                    buildDecodeImageType(DecodeImageType.NO_IMAGE)
                }
                R.id.rb_server_image -> {
                    configBean?.decodeImageType = DecodeImageType.SERVER_DECODE.codeType
                    buildDecodeImageType(DecodeImageType.SERVER_DECODE)
                }
                R.id.rb_local_image -> {
                    configBean?.decodeImageType = DecodeImageType.LOCAL_DECODE.codeType
                    buildDecodeImageType(DecodeImageType.LOCAL_DECODE)
                }
                R.id.rb_server_image_finger -> {
                    configBean?.decodeImageType =
                        DecodeImageType.SERVER_DECODE_FINGER.codeType
                    buildDecodeImageType(DecodeImageType.SERVER_DECODE_FINGER)
                }
                R.id.rb_local_image_finger -> {
                    configBean?.decodeImageType =
                        DecodeImageType.LOCAL_DECODE_FINGER.codeType
                    buildDecodeImageType(DecodeImageType.LOCAL_DECODE_FINGER)
                }
            }
            HHTipUtils.getInstance().showToast(baseContext, "操作成功")
        }
    }

    override fun onStop() {
        try {
            configBean?.let {
                SpUtlils.putString(
                    READ_CONFIG_KEY,
                    JsonUtils.gson.toJson(it)
                )
            }
        } catch (e: Exception) {
        }
        super.onStop()
    }
}